package com.iursp.service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import com.iursp.domain.model.role.AuthInterface;
import com.iursp.domain.model.user.CommonUser;
import com.iursp.mapper.role.AuthInterfaceMapper;


@Component("rbacService")
public class RbacServiceImpl implements RbacService {
	
	private Logger logger =  LoggerFactory.getLogger(RbacServiceImpl.class);
	
	@Autowired
	private AuthInterfaceMapper interfaceMapper;

	/**
	 * uri匹配工具 匹配角色和对应的url，如果数据库中配置的角色的访问路径没有 不予访问
	 */
	@SuppressWarnings("unused")
	private AntPathMatcher antPathMatcher = new AntPathMatcher();

	@Override
	public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
		// log.info("【RbacServiceImpl】 --hasPermission={}",
		// authentication.getPrincipal());
		Object principal = authentication.getPrincipal();

		boolean hasPermission = false;
		// 有可能是匿名的anonymous
		if (principal instanceof CommonUser) {
			// admin永远放回true
			if (StringUtils.equals("admin", ((CommonUser) principal).getUsername())) {
				hasPermission = true;
			} else {
				// Set<String> urls = sysMenuService.getUrlByname(((SysUser)
				// principal).getUsername());

				/*
				 * for (String url : urls) { if (antPathMatcher.match(url,
				 * request.getRequestURI())) { hasPermission = true; break; } }
				 */
			}
		}
		return hasPermission;
	}

	/**
	 * 
	 * @Title: hasPermissionThirdlib @Description: 第三方接口统一校验 @param: @param
	 * request @param: @param authentication @param: @return @return:
	 * boolean @throws
	 */
	@Override
	public boolean hasPermissionThirdlib(HttpServletRequest request, Authentication authentication) {
		logger.info("第三方接口统一进行校验");
		// Object principal = authentication.getPrincipal();
		boolean hasPermission = false;
		List<AuthInterface> list = new ArrayList<AuthInterface>();
		String app_id = request.getParameter("app_id");
		String app_secret = request.getParameter("app_secret");
		if (StringUtils.isNotEmpty(app_id) || StringUtils.isNotEmpty(app_secret)) {
			//去数据库校验
			 list = interfaceMapper.selectByPrimaryAppSecret(app_id,app_secret);
		}
		if(list!=null && !list.isEmpty()){
			hasPermission = true;
		}

		return hasPermission;
	}

	/**
	 * 直接返回true
	 * 
	 * @param authentication
	 * @param id
	 * @return
	 */
	public boolean checkUserId(Authentication authentication, int id) {
		return true;
	}

}
